<?php

namespace common\models\position;

use Yii;
use common\helpers\Url;

/**
 * This is the model class for table "{{%position_content}}".
 *
 * @property int $id
 * @property int $position_id 推荐位ID
 * @property string $title 标题
 * @property string $cover 封面图
 * @property string $uri 跳转地址
 * @property string $model 内部模型
 * @property int $model_id 内部模型ID
 * @property int $admin_id 管理员ID
 * @property int $listorder 排序
 * @property int $status 状态：0禁用，10启用
 * @property int $created_at 创建时间
 * @property int $updated_at 修改时间
 */
class PositionContent extends \common\base\ActiveRecord {

    use \common\traits\Constants;
    use \common\traits\TimestampBehavior;
    use \common\traits\QueryInstanceActiveRecord;

    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%position_content}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['position_id', 'model_id', 'admin_id', 'listorder', 'status', 'created_at', 'updated_at'], 'integer'],
            [['title', 'cover'], 'required'],
            [['title'], 'string', 'max' => 64],
            [['cover', 'uri'], 'string', 'max' => 255],
            [['model'], 'string', 'max' => 50],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'position_id' => '推荐位ID',
            'title' => '标题',
            'cover' => '封面图',
            'uri' => '跳转地址',
            'model' => '内部模型',
            'model_id' => '内部模型ID',
            'admin_id' => '管理员ID',
            'listorder' => '排序',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '修改时间',
        ];
    }

    public function getPosition() {
        return $this->hasOne(Position::className(), ['id' => 'position_id']);
    }

    public function getLink() {
        if ($this->uri) {
            return $this->uri;
        }
        if ($this->model == 'course') {
            return Url::h5('course/' . $this->model_id);
        }
        return '';
    }

    public function fields() {
        return [
            'id',
            'title',
            'thumb' => function() {
                return Url::toRemote($this->cover);
            },
            'link'
        ];
    }

}
